﻿using ActionSystem.Core.ComboLogic;
using ActionSystem.Core.Ranges;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using ActionSystem.Core.Utils;

namespace ActionSystem.Core.ComboLogic
{
    [PoolInitAttribute(typeof(GameObjectPool<SphereRangeBoxItem>), 50)]
    public class SphereRangeBoxItem : RangeBoxItem
    {
        public override Collider InitCollider()
        {
            return gameObject.AddComponent<SphereCollider>();
        }

        protected override void PutBackToPool()
        {
            if(!IsDeleted)
            {
                GameObjectPool<SphereRangeBoxItem>.Delete(this);
            }            
        }

        public override void SetRangeShape(IItem item)
        {
            base.SetRangeShape(item);
            SphereItem r = item as SphereItem;
            if (r != null)
            {
                var sph = hitBox as SphereCollider;
                if(sph != null)
                {
                    sph.transform.rotation = Quaternion.identity;
                    sph.center = Vector3.zero;
                    sph.transform.position = new Vector3(r.offset.x, r.offset.y, r.offset.z);
                    sph.radius = r.radius;
                }
            }
        }

        public override int HitDetect(int unityLayerMask)
        {
            if (value == null || unityLayerMask == 0)
            {
                return 0;
            }
            SphereItem sph = value as SphereItem;
            if (sph==null)
            {
                return 0;
            }
#if UNITY_EDITOR && DRAW_RANGE
            var defaultColor = XMLib.DrawUtility.D.color;
            XMLib.DrawUtility.D.color = Color.yellow;
            XMLib.DrawUtility.D.duration = 1 / 60f;
            var m3 = transform.localToWorldMatrix;
            XMLib.DrawUtility.D.DrawSphere(sph.radius, m3);
            XMLib.DrawUtility.D.color = defaultColor;
#endif
            int count = Physics.OverlapSphereNonAlloc(transform.position,sph.radius,hitColiderRes,unityLayerMask);
            for(int i =0;i<count;i++)
            {
                hitColiderRes[i].TryGetComponent<RangeBoxItem>(out hitRes[i]);
            }
            return count;
        }
    }
}


